package com.ict.web.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import com.ict.common.core.domain.entity.SysDept;
import com.ict.common.utils.SecurityUtils;
import com.ict.common.utils.StringUtils;
import com.ict.common.utils.uuid.IdUtils;
import com.ict.system.mapper.SysDeptMapper;
import com.ict.system.service.ISysDeptService;
import com.ict.system.service.ISysDictDataService;
import com.ict.system.service.ISysUserService;
import com.ict.web.constant.Constants;
import com.ict.web.constant.ProjectStatusEnum;
import com.ict.web.controller.file.domain.YzqFile;
import com.ict.web.controller.file.service.IYzqFileService;
import com.ict.web.domain.*;
import com.ict.web.dto.*;
import com.ict.web.mapper.LastCheckMapper;
import com.ict.web.mapper.PerformanceIndicatorsMapper;
import com.ict.web.mapper.ProjectManagementMapper;
import com.ict.web.mapper.ScoreMapper;
import com.ict.web.msg.domain.SysMsg;
import com.ict.web.msg.service.ISysMsgService;
import com.ict.web.msg.util.CreateMsgUtil;
import com.ict.web.service.IAnnualProjectPlanService;
import com.ict.web.service.IApprovalService;
import com.ict.web.service.IPerformanceService;
import com.ict.web.service.IProjectManagementService;
import com.ict.web.utils.pdf.RoleUtil;
import com.ict.web.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

import static com.ict.common.utils.PageUtils.startPage;

/**
 * 项目管理Service业务层处理
 *
 * @author ruoyi
 * @date 2022-02-14
 */
@Service
public class ProjectManagementServiceImpl extends ServiceImpl<ProjectManagementMapper, ProjectManagement> implements IProjectManagementService {
    @Resource
    private ProjectManagementMapper projectManagementMapper;

    @Resource
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private ProjectInfoServiceImpl projectInfoService;

    @Resource
    private IAnnualProjectPlanService annualProjectPlanService;

    @Resource
    private ISysDictDataService dictDataService;
    @Resource
    private IPerformanceService performanceService;
    @Resource
    private ISysDeptService sysDeptService;
    @Resource
    private ISysUserService userService;
    @Resource
    private IApprovalService approvalService;
    @Resource
    private IYzqFileService fileService;
    @Resource
    private ScoreMapper scoreMapper;
    @Resource
    private LastCheckMapper lastCheckMapper;
    @Resource
    private PerformanceIndicatorsMapper performanceIndicatorsMapper;
    @Resource
    private  ISysMsgService mySysMsg;
    /**
     * 查询项目管理
     *
     * @param proId 项目管理主键
     * @return 项目管理
     */
    @Override
    public ProjectManagementDetailsVo selectProjectManagementByProId(Long proId) {
        ProjectManagementDetailsVo bean = projectManagementMapper.selectProjectManagementByProId(proId);
        return bean;
    }

    /**
     * 查询项目管理列表
     *
     * @param dto 项目管理
     * @return 项目管理
     */
    @Override
    public List<ProjectManagementListVo> selectProjectManagementList(ProjectManagementListDto dto) {
        //未转三方的待处理
        List<String> pendings = new ArrayList<>();
        pendings.add(ProjectStatusEnum.APPLICATION_REVIEW_TO_BE_REVIEWED.get().getStatus());
        pendings.add(ProjectStatusEnum.ARRANGE_REVIEW_MEETING_TO_BE_EXTRACTED.get().getStatus());
        pendings.add(ProjectStatusEnum.COMMENTS_SUMMARY_TO_BE_APPROVED.get().getStatus());
        pendings.add(ProjectStatusEnum.ONLINE_PREQUALIFICATION_PENDING_ARRANGE.get().getStatus());
        pendings.add(ProjectStatusEnum.ON_SITE_DEMONSTRATION_TO_BE_REVIEWED.get().getStatus());
        pendings.add(ProjectStatusEnum.BIG_DATA_AUDIT_COMMENTS_SUMMARY_TO_BE_APPROVED.get().getStatus());
        pendings.add(ProjectStatusEnum.REVIEW_OF_THIRD_PARTY_APPROVAL_RESULTS_TO_BE_REVIEWED.get().getStatus());
        pendings.add(ProjectStatusEnum.SCHEME_DECLARATION_UPDATE_TO_BE_APPROVED.get().getStatus());
        pendings.add(ProjectStatusEnum.COMPLIANCE_REVIEW_TO_BE_REVIEWED.get().getStatus());
        pendings.add(ProjectStatusEnum.SCHEME_DECLARATION_SUBMISSION_SUBMITTED.get().getStatus());
        pendings.add(ProjectStatusEnum.DECLARATION_SUBMISSION_SUBMITTED.get().getStatus());
        //未转三方的已处理
        List<String> processeds = new ArrayList<>();
        processeds.add(ProjectStatusEnum.APPLICATION_REVIEW_REJECT.get().getStatus());
        processeds.add(ProjectStatusEnum.APPLICATION_REVIEW_RETURN_MODIFICATION.get().getStatus());
        processeds.add(ProjectStatusEnum.SUMMARY_AND_RETURN_OF_COMMENTS.get().getStatus());
        processeds.add(ProjectStatusEnum.ON_SITE_DEMONSTRATION_RETURN_RESTATEMENT.get().getStatus());
        processeds.add(ProjectStatusEnum.ON_SITE_DEMONSTRATION_NEEDS_TO_BE_MODIFIED.get().getStatus());
        processeds.add(ProjectStatusEnum.THIRD_PARTY_APPROVAL_TO_BE_REVIEWED.get().getStatus());
        processeds.add(ProjectStatusEnum.REVIEW_OF_THIRD_PARTY_APPROVAL_RESULTS_RETURN_RESTATEMENT.get().getStatus());
        processeds.add(ProjectStatusEnum.BIG_DATA_AUDIT_SUMMARY_AND_RETURN_OF_COMMENTS.get().getStatus());
        processeds.add(ProjectStatusEnum.COMPLIANCE_REVIEW_REJECTED.get().getStatus());
        processeds.add(ProjectStatusEnum.FINANCIAL_APPROVAL_AND_FILING_TO_BE_REVIEWED.get().getStatus());
        processeds.add(ProjectStatusEnum.ONLINE_PREQUALIFICATION_PENDING_APPROVAL.get().getStatus());
        processeds.add(ProjectStatusEnum.MILESTONE_MANAGEMENT_TO_BE_SUBMITTED.get().getStatus());
        processeds.add(ProjectStatusEnum.FINAL_ACCEPTANCE_RECORD_SUBMITTED.get().getStatus());
        processeds.add(ProjectStatusEnum.CONTRACT_FILING_TO_BE_SUBMITTED.get().getStatus());
        processeds.add(ProjectStatusEnum.ACCEPT_NOT_TASK.get().getStatus());
        processeds.add(ProjectStatusEnum.SCHEME_DECLARATION_TO_BE_SUBMITTED.get().getStatus());
        processeds.add(ProjectStatusEnum.COMPLIANCE_REVIEW_TO_BE_SUBMITTED.get().getStatus());
        processeds.add(ProjectStatusEnum.PERFORMANCE_EVALUATION_TO_BE_EVALUATED.get().getStatus());
        processeds.add(ProjectStatusEnum.PRELIMINARY_INSPECTION_AND_FILING_TO_BE_SUBMITTED.get().getStatus());
        processeds.add(ProjectStatusEnum.ARRANGE_REVIEW_TO_BE_ACCEPTED.get().getStatus());
        processeds.add(ProjectStatusEnum.ACCEPT_TASKED.get().getStatus());
        processeds.add(ProjectStatusEnum.SCHEME_DECLARATION_UPDATE_TO_BE_SUBMITTED.get().getStatus());
        processeds.add(ProjectStatusEnum.APPLICATION_UPDATE_TURN_DOWN.get().getStatus());
        processeds.add(ProjectStatusEnum.FINAL_ACCEPTANCE_RECORD_TO_BE_SUBMITTED.get().getStatus());
        processeds.add(ProjectStatusEnum.SCHEME_DECLARATION_UPDATE_RETURN_MODIFICATION.get().getStatus());
        processeds.add(ProjectStatusEnum.REVIEW_OF_THIRD_PARTY_APPROVAL_RESULTS_HAS_BEEN_PASSED.get().getStatus());
        //转三方的待处理
        List<String> third = new ArrayList<>();
        third.add(ProjectStatusEnum.ARRANGE_REVIEW_MEETING_TO_BE_EXTRACTED.get().getStatus());
        third.add(ProjectStatusEnum.ON_SITE_DEMONSTRATION_TO_BE_REVIEWED.get().getStatus());
        third.add(ProjectStatusEnum.COMMENTS_SUMMARY_TO_BE_APPROVED.get().getStatus());
        third.add(ProjectStatusEnum.ONLINE_PREQUALIFICATION_PENDING_ARRANGE.get().getStatus());
        third.add(ProjectStatusEnum.SCHEME_DECLARATION_UPDATE_TO_BE_APPROVED.get().getStatus());
        third.add(ProjectStatusEnum.SCHEME_DECLARATION_UPDATE_TO_BE_SUBMITTED.get().getStatus());
        List<String> pendingThird = new ArrayList<>();
        pendingThird.addAll(pendings);
        List<String> pendingThirds = pendingThird.stream().filter(a->!third.contains(a)).collect(Collectors.toList());
        //转三方的已处理
        List<String> processedThirds = new ArrayList<>();
        processedThirds.addAll(third);
        processedThirds.addAll(processeds);

        //已完成
        ArrayList<String> completeds = new ArrayList<>();
        completeds.add(ProjectStatusEnum.PERFORMANCE_EVALUATION_HAS_BEEN_EVALUATED.get().getStatus());
        completeds.add(ProjectStatusEnum.APPLICATION_REVIEW_PASSED.get().getStatus());
        completeds.add(ProjectStatusEnum.APPLICATION_UPDATE_PASSED.get().getStatus());

        if(StringUtils.isNotEmpty(dto.getStatus())){
            List<String> statusCollect = ProjectStatusEnum.getEnumByStatusDes(dto.getStatus());
            dto.setStatusCollect(statusCollect);
        }

        //发改财政根据处理状态查询：(转三方/未转三方)
        if(RoleUtil.getUserRole(Constants.ROLE_TYPE_COMMISSION)){
            List<ProjectManagementListVo> commissionProjectManagementList = projectManagementMapper.commissionProjectManagementList(dto);
            return pageList(commissionProjectManagementList,dto,pendings,completeds,processeds,pendingThirds,processedThirds);
        }
        //大数据局根据处理状态查询：(转三方/未转三方)
        List<ProjectManagementListVo> projectManagementListVos = projectManagementMapper.selectProjectManagementList(dto);
        return pageList(projectManagementListVos,dto,pendings,completeds,processeds,pendingThirds,processedThirds);
    }

    @Override
    public List<ProjectManagementListVo> selectProjectList(ProjectManagementDto dto) {
        ProjectManagementListDto listDto = new ProjectManagementListDto();
        BeanUtils.copyProperties(dto,listDto);
        List<ProjectManagementListVo> listVos = selectProjectManagementList(listDto);
        return  pageBySubList(listVos, dto.getPageSize(), dto.getPageNum());
    }

    /**
     * 大数据局/发改财政根据处理状态查询
     * @param list
     * @param dto
     * @param pendings
     * @param completeds
     * @param processeds
     * @param pendingThirds
     * @param processedThirds
     * @return
     */
    public  List pageList(List<ProjectManagementListVo> list,ProjectManagementListDto dto,List<String> pendings,List<String> completeds,
                          List<String> processeds,List<String> pendingThirds,List<String> processedThirds){

        list.stream().forEach(s -> {
            s.setStagName(ProjectStatusEnum.getEnum(s.getIsState()).getStage());
            s.setNodeName(ProjectStatusEnum.getEnum(s.getIsState()).getNode());
            //未转三方
            if(StringUtils.isNull(s.getTripartiteId())){
                if (pendings.contains(s.getIsState())){
                    s.setIsStateName("待处理");
                } else if (completeds.contains(s.getIsState())) {
                    s.setIsStateName("已完成");
                } else if (processeds.contains(s.getIsState())) {
                    s.setIsStateName("已处理");
                }
                //转三方
            }else {
                if (pendingThirds.contains(s.getIsState())){
                    s.setIsStateName("待处理");
                } else if (completeds.contains(s.getIsState())) {
                    s.setIsStateName("已完成");
                } else if (processedThirds.contains(s.getIsState())) {
                    s.setIsStateName("已处理");
                }
            }

        });
        if (StringUtils.isNotNull(dto.getProcessingStatus())) {
            String isStateName;
            switch (dto.getProcessingStatus()) {
                case "0":
                    isStateName="待处理";
                    break;
                case "1":
                    isStateName="已处理";
                    break;
                case "2":
                    isStateName="已完成";
                    break;
                default:
                    throw new IllegalStateException("处理状态传值有误！！" + dto.getProcessingStatus());
            }
            list = list.stream().filter(
                    s -> s.getIsStateName().equals(isStateName)).collect(Collectors.toList());
        }
        return list;
    }
    /**
     * 利用subList方法进行分页
     * @param list 分页数据
     * @param pagesize  页面大小
     * @param currentPage   当前页面
     */
    public static List pageBySubList(List list, int pagesize, int currentPage) {
        int totalcount = list.size();
        int pagecount = 0;
        List subList;
        int m = totalcount % pagesize;
        if (m > 0) {
            pagecount = totalcount / pagesize + 1;
        } else {
            pagecount = totalcount / pagesize;
        }
        if (m == 0) {
            subList = list.subList((currentPage - 1) * pagesize, pagesize * (currentPage));
        } else {
            if (currentPage == pagecount) {
                subList = list.subList((currentPage - 1) * pagesize, totalcount);
            } else {
                subList = list.subList((currentPage - 1) * pagesize, pagesize * (currentPage));
            }
        }
        return subList;
    }
    /**
     * 查询我的项目管理列表
     *
     * @param dto 项目管理
     * @return 项目管理
     */
    @Override
    public PageInfo<ProjectManagementListVo> selectMyProject(ProjectManagementListDto dto) {
        //待提交
        ArrayList<String> pendingSubmission = new ArrayList<>();
        pendingSubmission.add(ProjectStatusEnum.STATEMENT_NOT_SUBMITTED.get().getStatus());
        pendingSubmission.add(ProjectStatusEnum.APPLICATION_REVIEW_RETURN_MODIFICATION.get().getStatus());
        pendingSubmission.add(ProjectStatusEnum.SCHEME_DECLARATION_TO_BE_SUBMITTED.get().getStatus());
        pendingSubmission.add(ProjectStatusEnum.SUMMARY_AND_RETURN_OF_COMMENTS.get().getStatus());
        pendingSubmission.add(ProjectStatusEnum.ON_SITE_DEMONSTRATION_RETURN_RESTATEMENT.get().getStatus());
        pendingSubmission.add(ProjectStatusEnum.ON_SITE_DEMONSTRATION_NEEDS_TO_BE_MODIFIED.get().getStatus());
        pendingSubmission.add(ProjectStatusEnum.FINANCIAL_APPROVAL_AND_FILING_TO_BE_REVIEWED.get().getStatus());
        pendingSubmission.add(ProjectStatusEnum.CONTRACT_FILING_TO_BE_SUBMITTED.get().getStatus());
        pendingSubmission.add(ProjectStatusEnum.MILESTONE_MANAGEMENT_TO_BE_SUBMITTED.get().getStatus());
        pendingSubmission.add(ProjectStatusEnum.COMPLIANCE_REVIEW_TO_BE_SUBMITTED.get().getStatus());
        pendingSubmission.add(ProjectStatusEnum.COMPLIANCE_REVIEW_REJECTED.get().getStatus());
        pendingSubmission.add(ProjectStatusEnum.PRELIMINARY_INSPECTION_AND_FILING_TO_BE_SUBMITTED.get().getStatus());
        pendingSubmission.add(ProjectStatusEnum.FINAL_ACCEPTANCE_RECORD_TO_BE_SUBMITTED.get().getStatus());
        pendingSubmission.add(ProjectStatusEnum.APPLICATION_UPDATE_TO_BE_SUBMITTED.get().getStatus());
        pendingSubmission.add(ProjectStatusEnum.SCHEME_DECLARATION_UPDATE_TO_BE_SUBMITTED.get().getStatus());
        pendingSubmission.add(ProjectStatusEnum.APPLICATION_UPDATE_RETURN_MODIFICATION.get().getStatus());
        pendingSubmission.add(ProjectStatusEnum.SCHEME_DECLARATION_UPDATE_RETURN_MODIFICATION.get().getStatus());
        pendingSubmission.add(ProjectStatusEnum.REVIEW_OF_THIRD_PARTY_APPROVAL_RESULTS_HAS_BEEN_PASSED.get().getStatus());
        pendingSubmission.add(ProjectStatusEnum.REVIEW_OF_THIRD_PARTY_APPROVAL_RESULTS_RETURN_RESTATEMENT.get().getStatus());
        pendingSubmission.add(ProjectStatusEnum.PROGRAM_PREREVIEW_RETURN_FOR_RETRIAL.get().getStatus());
        //待审批
        ArrayList<String> pendings = new ArrayList<>();
        pendings.add(ProjectStatusEnum.APPLICATION_REVIEW_TO_BE_REVIEWED.get().getStatus());
        pendings.add(ProjectStatusEnum.DECLARATION_SUBMISSION_SUBMITTED.get().getStatus());
        pendings.add(ProjectStatusEnum.ARRANGE_REVIEW_MEETING_TO_BE_EXTRACTED.get().getStatus());
        pendings.add(ProjectStatusEnum.ACCEPT_NOT_TASK.get().getStatus());
        pendings.add(ProjectStatusEnum.COMMENTS_SUMMARY_TO_BE_APPROVED.get().getStatus());
        pendings.add(ProjectStatusEnum.ON_SITE_DEMONSTRATION_TO_BE_REVIEWED.get().getStatus());
        pendings.add(ProjectStatusEnum.REVIEW_OF_THIRD_PARTY_APPROVAL_RESULTS_TO_BE_REVIEWED.get().getStatus());
        pendings.add(ProjectStatusEnum.BIG_DATA_AUDIT_COMMENTS_SUMMARY_TO_BE_APPROVED.get().getStatus());
        pendings.add(ProjectStatusEnum.COMPLIANCE_REVIEW_TO_BE_REVIEWED.get().getStatus());
        pendings.add(ProjectStatusEnum.APPLICATION_UPDATE_TO_BE_APPROVED.get().getStatus());
        pendings.add(ProjectStatusEnum.SCHEME_DECLARATION_UPDATE_TO_BE_APPROVED.get().getStatus());
        pendings.add(ProjectStatusEnum.ONLINE_PREQUALIFICATION_PENDING_APPROVAL.get().getStatus());
        pendings.add(ProjectStatusEnum.ONLINE_PREQUALIFICATION_PENDING_ARRANGE.get().getStatus());
        pendings.add(ProjectStatusEnum.ONLINE_PREQUALIFICATION_PENDING_APPROVAL_AGAIN.get().getStatus());
        pendings.add(ProjectStatusEnum.PROGRAM_PREREVIEW_PENDING.get().getStatus());
        //已完成
        ArrayList<String> completeds = new ArrayList<>();
        completeds.add(ProjectStatusEnum.APPLICATION_REVIEW_REJECT.get().getStatus());
        completeds.add(ProjectStatusEnum.FINAL_ACCEPTANCE_RECORD_SUBMITTED.get().getStatus());
        completeds.add(ProjectStatusEnum.PERFORMANCE_EVALUATION_TO_BE_EVALUATED.get().getStatus());
        completeds.add(ProjectStatusEnum.PERFORMANCE_EVALUATION_HAS_BEEN_EVALUATED.get().getStatus());
        completeds.add(ProjectStatusEnum.APPLICATION_REVIEW_PASSED.get().getStatus());
        completeds.add(ProjectStatusEnum.APPLICATION_UPDATE_TURN_DOWN.get().getStatus());
        completeds.add(ProjectStatusEnum.SCHEME_DECLARATION_SUBMISSION_SUBMITTED.get().getStatus());
        completeds.add(ProjectStatusEnum.ARRANGE_REVIEW_TO_BE_ACCEPTED.get().getStatus());
        completeds.add(ProjectStatusEnum.ACCEPT_TASKED.get().getStatus());
        completeds.add(ProjectStatusEnum.ONLINE_PREQUALIFICATION_APPROVED.get().getStatus());
        completeds.add(ProjectStatusEnum.OPINION_SUMMARY_APPROVED.get().getStatus());
        completeds.add(ProjectStatusEnum.THE_ONSITE_DEMONSTRATION_HAS_BEEN_PASSED.get().getStatus());
        completeds.add(ProjectStatusEnum.FINANCIAL_APPROVAL_AND_FILING_HAS_BEEN_PASSED.get().getStatus());
        completeds.add(ProjectStatusEnum.CONTRACT_FILING_SUBMITTED.get().getStatus());
        completeds.add(ProjectStatusEnum.MILESTONE_MANAGEMENT_SUBMITTED.get().getStatus());
        completeds.add(ProjectStatusEnum.COMPLIANCE_REVIEW_SUBMITTED.get().getStatus());
        completeds.add(ProjectStatusEnum.COMPLIANCE_REVIEW_HAS_BEEN_PASSED.get().getStatus());
        completeds.add(ProjectStatusEnum.PRELIMINARY_INSPECTION_AND_FILING_SUBMITTED.get().getStatus());
        completeds.add(ProjectStatusEnum.TURN_SENT_TASK.get().getStatus());
        completeds.add(ProjectStatusEnum.BIG_DATA_AUDIT_OPINION_SUMMARY_APPROVED.get().getStatus());
        completeds.add(ProjectStatusEnum.BIG_DATA_AUDIT_SUMMARY_AND_RETURN_OF_COMMENTS.get().getStatus());
        completeds.add(ProjectStatusEnum.APPLICATION_UPDATE_PASSED.get().getStatus());
        completeds.add(ProjectStatusEnum.SCHEME_DECLARATION_UPDATE_PASSED.get().getStatus());
        completeds.add(ProjectStatusEnum.ONLINE_PREQUALIFICATION_APPROVED_AGAIN.get().getStatus());
        completeds.add(ProjectStatusEnum.PROGRAM_PREREVIEW_PASS.get().getStatus());



        if(StringUtils.isNotEmpty(dto.getStatus())){
            List<String> statusCollect = ProjectStatusEnum.getEnumByStatusDes(dto.getStatus());
            dto.setStatusCollect(statusCollect);
        }

        if (StringUtils.isNotNull(dto.getProcessingStatus())) {
            List<String> statusCollect = dto.getStatusCollect();
            switch (dto.getProcessingStatus()) {
                case "0":
                    statusCollect.addAll(pendingSubmission);
                    break;
                case "1":
                    statusCollect.addAll(pendings);
                    break;
                case "2":
                    statusCollect.addAll(completeds);
                    break;
            }
        }

        SysDept sysDept = sysDeptMapper.selectDeptById(SecurityUtils.getDeptId());
        String company = sysDept.getDeptName();
        dto.setCompany(company);
        String stag = dictDataService.selectDictLabel("sys_stag", dto.getStag());
        dto.setStag(stag);
        dto.setUserId(SecurityUtils.getUserId());
        startPage();
        List<ProjectManagementListVo> voList = projectManagementMapper.selectMyProject(dto);
        voList.stream().forEach(s -> {
            if (pendingSubmission.contains(s.getIsState())) {
                s.setIsStateName("待提交");
            } else if (pendings.contains(s.getIsState())) {
                s.setIsStateName("待审批");
            } else if (completeds.contains(s.getIsState())) {
                s.setIsStateName("已完成");
            }
            //项目单位不展示绩效考评节点
            if(ProjectStatusEnum.PERFORMANCE_EVALUATION_TO_BE_EVALUATED.get().getStatus().equals(s.getIsState())||
                    ProjectStatusEnum.PERFORMANCE_EVALUATION_HAS_BEEN_EVALUATED.get().getStatus().equals(s.getIsState())){
                s.setStag(ProjectStatusEnum.FINAL_ACCEPTANCE_RECORD_SUBMITTED.get().getStage());
                s.setNode(ProjectStatusEnum.FINAL_ACCEPTANCE_RECORD_SUBMITTED.get().getNode());
            }
        });
        return new PageInfo<>(voList);
    }


    /**
     * 新增项目管理
     *
     * @param dto 项目管理
     * @return 结果
     */
    @Override
    public Long insertProjectManagement(ProjectManagementAddDto dto) {
        ProjectManagement projectManagement = ProjectManagementAddDto.of(dto);
        //设置项目单位
        SysDept sysDept = sysDeptMapper.selectDeptById(SecurityUtils.getDeptId());
        projectManagement.setCompany(sysDept.getDeptName());

        //添加审核进度
        Long userId = SecurityUtils.getUserId();
        String userName=userService.selectUserById(userId).getUserName();

        if ("0".equals(dto.getNature())&&"0".equals(dto.getIsState())){
            //年度申报
            approvalService.save(new Approval(IdUtils.snowId(),projectManagement.getProId(),ProjectStatusEnum.DECLARATION_SUBMISSION_SUBMITTED.get().getStage(),
                    ProjectStatusEnum.DECLARATION_SUBMISSION_SUBMITTED.get().getNode(),LocalDateTime.now(),LocalDateTime.now(),SecurityUtils.getNickName(),ProjectStatusEnum.DECLARATION_SUBMISSION_SUBMITTED.get().getStatus(),
                    "/",null, null,dto.getProjectProposal(), LocalDateTime.now(),Approval.APPROVAL_TYPE_PROJECT_MANAGE));
        }else if ("1".equals(dto.getNature())&&"1".equals(dto.getIsState())){
            //增补申报
            approvalService.save(new Approval(IdUtils.snowId(),projectManagement.getProId(),ProjectStatusEnum.DECLARATION_SUBMISSION_SUBMITTED.get().getStage(),
                    ProjectStatusEnum.DECLARATION_SUBMISSION_SUBMITTED.get().getNode(),LocalDateTime.now(),LocalDateTime.now(),SecurityUtils.getNickName(),ProjectStatusEnum.DECLARATION_SUBMISSION_SUBMITTED.get().getStatus(),
                    "/",null, null,dto.getProjectProposal(), LocalDateTime.now(),Approval.APPROVAL_TYPE_PROJECT_MANAGE));
            approvalService.save(new Approval(IdUtils.snowId(),projectManagement.getProId(),ProjectStatusEnum.APPLICATION_REVIEW_TO_BE_REVIEWED.get().getStage(),
                    ProjectStatusEnum.APPLICATION_REVIEW_TO_BE_REVIEWED.get().getNode(),LocalDateTime.now(),null,null,ProjectStatusEnum.APPLICATION_REVIEW_TO_BE_REVIEWED.get().getStatus(),
                    "/",null, null,null, LocalDateTime.now(),Approval.APPROVAL_TYPE_PROJECT_MANAGE));
        }
        projectManagementMapper.insert(projectManagement);
        return projectManagement.getProId();
    }

    /**
     * 修改项目管理
     *
     * @param dto 项目管理
     * @return 结果
     */
    @Override
    public int updateProjectManagement(ProjectManagementEditDto dto, Long proId) {
        ProjectManagement bean = projectManagementMapper.selectById(proId);
        BeanUtils.copyProperties(dto, bean);
        bean.setUpdateTime(LocalDateTime.now());
        Assert.isTrue((dto.getIsState().equals(Constants.APPLICATION_REVIEW_PASSED) ||
                dto.getIsState().equals(Constants.APPLICATION_REVIEW_RETURN_MODIFICATION) ||
                dto.getIsState().equals(Constants.APPLICATION_REVIEW_REJECT)), "状态值——信息错误");
        projectManagementMapper.updateById(bean);
        ProjectManagementListDto listDto = new ProjectManagementListDto();
        //判断，是否已经已经将所有待审核 审核完成，是：将状态改为 “已审核”;否：不变
        List<ProjectManagementListVo> voList = projectManagementMapper.selectProjectManagementList(listDto);
        int x = 0;
        for (ProjectManagementListVo vo : voList) {
            if (vo.getIsState().equals(Constants.APPLICATION_REVIEW_TO_BE_REVIEWED)) {
                break;
            } else {
                x++;
            }
        }
        if (x == voList.size()) {
            AnnualProjectPlan planBean = annualProjectPlanService.getById(bean.getAnnualId());
            planBean.setIsState(Constants.ANNUAL_PROJECT_PLAN_APPROVED);
            annualProjectPlanService.updateById(planBean);
        }
        return x;
    }

    /**
     * 批量删除项目管理
     *
     * @param proId 需要删除的项目管理主键
     * @return 结果
     */
    @Override
    public int deleteProjectManagementByProIds(Long proId) {
        ProjectManagement bean = projectManagementMapper.selectById(proId);
        System.out.println("项目管理：" + projectManagementMapper.selectById(proId));
        Assert.isTrue(bean != null, "数据不存在！");
        bean.setIsDelete("1");
        return projectManagementMapper.updateById(bean);
    }

    /**
     * 根据评审任务id查询列表
     * @param reviewTaskId
     * @return
     */
    @Override
    public ProjectManagementDetailsVo selectProjectManagementListByReviewIds(Long reviewTaskId) {
        return projectManagementMapper.selectProjectManagementListByReviewIds(reviewTaskId);
    }

    /**
     * 绩效统计列表查询
     * @param queryDto
     * @return
     */
    @Override
    public List<PerformanceStatisticsListVo> performanceStatisticsList(QueryPerformanceStatisticsDto queryDto){
        List<PerformanceStatisticsListVo> voList = projectManagementMapper.selectPerformanceStatisticsVoList(queryDto);
        voList.stream().forEach(s->{
            LocalDate endTime = s.getEndTime();
            //考核结束时间暂定为大于终验时间半年
            s.setEndTime(endTime.plusMonths(6));
        });
        return voList;
    }

    /**
     * 绩效统计详情
     * @param proId
     * @return
     */
    @Override
    public PerformanceStatisticsDetailVo selectPerformanceStatisticsByIdProId(Long proId){
        PerformanceStatisticsDetailVo statisticsDetailVo = new PerformanceStatisticsDetailVo();
        JSONObject jsonObject = testValue();
        ProjectManagement projectManagement = projectManagementMapper.selectById(proId);
        BeanUtils.copyProperties(projectManagement,statisticsDetailVo);
        AnnualProjectPlanDetailsVo annualProjectPlanDetailsVo = annualProjectPlanService.selectAnnualProjectPlanByPlanId(projectManagement.getPlanId());
        statisticsDetailVo.setAnnulProjectPlanName(annualProjectPlanDetailsVo.getName());
        PerformanceDetailVo performanceDetailVo = performanceService.selectPerformanceByPerId(projectManagement.getPerId());
        Assert.isTrue(StringUtils.isNotNull(performanceDetailVo),"绩效指标不存在!!!");

        LambdaQueryWrapper<Score> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Score::getProId,proId)
                .eq(Score::getIsDelete,Constants.DELETE_STATUS_NORMAL);
        Score score = scoreMapper.selectOne(queryWrapper);
        statisticsDetailVo.setScore(score.getScore());

        LambdaQueryWrapper<LastCheck> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(LastCheck::getLastCheckId,projectManagement.getLastCheckId())
                .eq(LastCheck::getIsDelete,Constants.DELETE_STATUS_NORMAL);
        LastCheck lastCheck = lastCheckMapper.selectOne(lambdaQueryWrapper);
        //考核开始时间为终验时间
        LocalDateTime localDateTime = lastCheck.getLastAdoptTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        String startTime = String.valueOf(localDateTime).substring(0,String.valueOf(localDateTime).lastIndexOf("T"));
        statisticsDetailVo.setStartTime(startTime);
        //考核时间暂定为大于终验时间半年
        LocalDateTime localDateTimeEndTime = localDateTime.plusMonths(6);
        String endTime = String.valueOf(localDateTimeEndTime).substring(0,String.valueOf(localDateTimeEndTime).lastIndexOf("T"));
        statisticsDetailVo.setEndTime(endTime);
        //有正确数据后取消此处注释
//        statisticsDetailVo.setStartTime(lastCheck.getCreateTime());


        //计算绩效得分
        double sum = 0d;
//        performanceIndicatorsList.forEach(data->{
//           if (data.getIndicatorsName().equals(testValue().get("cpuAvg"))){
//               data.getPerformanceRules().forEach(rules->{
//
//               });
//           }
//        });

//        绩效指标
        List<PerIndectorsDetailsVo> perIndectorsDetailsVos = performanceIndicatorsMapper.selectPerformanceIndicatorsDetail(projectManagement.getPerId());
        statisticsDetailVo.setPerIndectorsDetailsVos(perIndectorsDetailsVos);
        return statisticsDetailVo;
    }

    /**
     * 获取项目单位列表(三方机构加上大数据局)
     * @return
     */
    @Override
    public List<String> getCompany() {
        SysDept sysDept = new SysDept();
        sysDept.setParentId(102L);
        List<SysDept> sysDeptList = sysDeptMapper.selectDeptList(sysDept);
        List<String> list = new ArrayList<>();
        sysDeptList.stream().forEach(s->{
            list.add(s.getDeptName());
        });
        return list;
    }
    /**
     * 获取项目申报单位列表(委办局下面的部门（除大数据局）)
     * @return
     */
    @Override
    public List<String> selectApplyCompany() {
        List<ProjectInfo> infoList = projectInfoService.list(null);
        List<String> collect = infoList.stream().map(ProjectInfo::getProCompany).distinct()
                .filter(s->s!=null).collect(Collectors.toList());
        return collect;
    }

    @Override
    public HashMap<String,String> projectCount() {
        HashMap<String, String> map = new HashMap<>();
        Long deptId = SecurityUtils.getDeptId();
        SysDept sysDept = sysDeptService.selectDeptById(deptId);
        String deptName=sysDept.getDeptName();
        Long userId = SecurityUtils.getUserId();
        if("区大数据局".equals(deptName)){
            deptName=null;
            userId=null;
        }
        //项目申报
        map.put("apply",projectManagementMapper.projectCount(deptName,userId,ProjectStatusEnum.STATEMENT_NOT_SUBMITTED.get().getStage()));
        //方案申报
        map.put("schemeDeclaration",projectManagementMapper.projectCount(deptName,userId,ProjectStatusEnum.SCHEME_DECLARATION_TO_BE_SUBMITTED.get().getStage()));
        //项目实施
        map.put("implement",projectManagementMapper.projectCount(deptName,userId,ProjectStatusEnum.CONTRACT_FILING_TO_BE_SUBMITTED.get().getStage()));
        //项目验收
        map.put("check",projectManagementMapper.projectCount(deptName,userId,ProjectStatusEnum.COMPLIANCE_REVIEW_TO_BE_SUBMITTED.get().getStage()));
        return map;
    }

    @Override
    public void createMsg(Long proId,String info) {
        ProjectManagement projectManagement = projectManagementMapper.selectById(proId);
        Assert.isTrue(StringUtils.isNotNull(projectManagement),"未找到该项目信息");
        QueryWrapper<SysMsg> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("receive_user_id", projectManagement.getUserId());
        queryWrapper.eq("resource_type", SysMsg.RESOURCE_TYPE_UNIT);
        queryWrapper.eq("resource_id", projectManagement.getProId()+projectManagement.getIsState());
        queryWrapper.apply(true, "TO_DAYS(NOW())-TO_DAYS(create_time) = 0");
        List<SysMsg> msgList = mySysMsg.list(queryWrapper);
        Assert.isTrue(StringUtils.isEmpty(msgList),"今日已催办");
        String content=null;
        if(StringUtils.isEmpty(info)) {
             content = CreateMsgUtil.PASS_DO_STH + projectManagement.getName() + CreateMsgUtil.PASS_DO;
        }else {
            content=info;
        }
        CreateMsgUtil.createMsg(content, projectManagement.getUserId(), null, CreateMsgUtil.PASS_DO_STH_TITLE, SysMsg.RESOURCE_TYPE_UNIT, String.valueOf(projectManagement.getProId() + projectManagement.getIsState()), null);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int retreat(Long proId) {
        ProjectManagement management = projectManagementMapper.selectById(proId);
        Assert.isTrue(StringUtils.isNotNull(management),"未找到该项目信息");
        List<String> list = Arrays.asList(ProjectStatusEnum.STATEMENT_NOT_SUBMITTED.get().getStatus(),
                ProjectStatusEnum.DECLARATION_SUBMISSION_SUBMITTED.get().getStatus(),
                ProjectStatusEnum.APPLICATION_REVIEW_TO_BE_REVIEWED.get().getStatus());
        Assert.isTrue(list.contains(management.getIsState()),"项目单位状态为：申报提交待提交、申报提交已提交、申报审核待审核时，才能撤回！");
        //年度申报
        int delete;
        if(ProjectManagement.PROJECT_DECLARE.equals(management.getNature())){
            //更新信息
            List<SysMsg> msgList = mySysMsg.lambdaQuery().eq(SysMsg::getResourceId, String.valueOf(proId)).list();
            if(StringUtils.isNotEmpty(msgList)){
                List<String> idList = msgList.stream().map(SysMsg::getId).collect(Collectors.toList());
                mySysMsg.removeByIds(idList);
            }
            //年度计划更新数据
            AnnualProjectPlan projectPlan = annualProjectPlanService.getById(management.getPlanId());
            projectPlan.setNumberItems(projectPlan.getNumberItems()-1);
            String company = management.getCompany();
            List<ProjectManagement> projectManagementList=projectManagementMapper.selectList(
                    new QueryWrapper<ProjectManagement>()
                            .eq("plan_id",projectPlan.getPlanId())
                            .eq("is_delete",Constants.DELETE_STATUS_NORMAL));
            List<String> companyList = projectManagementList.stream().map(ProjectManagement::getCompany).collect(Collectors.toList());
            if(!companyList.contains(company)){
                projectPlan.setNumberProjectUnits(projectPlan.getNumberProjectUnits()-1);
            }
            projectPlan.setTotalInvestmentEstimation(projectPlan.getTotalInvestmentEstimation().subtract(management.getInvestmentEstimation()));
            switch (management.getType()){
                case ProjectManagement.PROJECT_DECLARE:
                case ProjectManagement.SCHEME_DECLARE:
                    projectPlan.setConstructionProjects(projectPlan.getConstructionProjects()-1);
                    break;
                case ProjectManagement.PROJECT_IMPLEMENTATION:
                    projectPlan.setPurchaseItems(projectPlan.getPurchaseItems()-1);
                    break;
                case ProjectManagement.PROJECT_ACCEPTANCE:
                    projectPlan.setOperationMaintenance(projectPlan.getOperationMaintenance()-1);
                    break;
                case ProjectManagement.PROJECT_OTHER:
                    projectPlan.setOther(projectPlan.getOther()-1);
                    break;
            }
            annualProjectPlanService.updateById(projectPlan);
            //审核进程删除
            List<Approval> approvalList = approvalService.lambdaQuery().eq(Approval::getPlanId, management.getProId()).list();
            if(StringUtils.isNotEmpty(approvalList)){
                List<Long> idList = approvalList.stream().map(Approval::getApprovalId).collect(Collectors.toList());
                approvalService.removeByIds(idList);
            }
            //项目信息删除
            delete = projectManagementMapper.deleteById(proId);
            //增补申报
        }else {
            //审核进程删除
            List<Approval> approvalList = approvalService.lambdaQuery().eq(Approval::getPlanId, management.getProId()).list();
            if(StringUtils.isNotEmpty(approvalList)){
                List<Long> idList = approvalList.stream().map(Approval::getApprovalId).collect(Collectors.toList());
                approvalService.removeByIds(idList);
            }
            //项目信息删除
            delete = projectManagementMapper.deleteById(proId);
        }
        return delete;
    }

    @Override
    public boolean deleteFile(Long approvalId) {
        Assert.isTrue(RoleUtil.getUserRole(Constants.ROLE_TYPE_BIGDATA)||RoleUtil.getUserRole(Constants.ROLE_TYPE_THIRD),
                "现场论证文件删除，只有角色为大数据局管理员或者三方机构才能操作");
        Approval approval = approvalService.getById(approvalId);
        approval.setApprovalDatabase(null);
        return approvalService.updateById(approval);
    }

    @Override
    public boolean uploadPorFile(Long approvalId, YzqFile file) {
        Assert.isTrue(StringUtils.isNotEmpty(file.getFileName()),"上传文件名不能为空");
        Assert.isTrue(StringUtils.isNotEmpty(file.getFileUrl()),"上传文件路径不能为空");
        YzqFile yzqFile = new YzqFile();
        yzqFile.setId(String.valueOf(IdUtils.snowId()));
        yzqFile.setFileName(file.getFileName());
        yzqFile.setFileUrl(file.getFileUrl());
        yzqFile.setDelFlag(ExtractExpert.DELETE_STATUS_NORMAL);
        fileService.save(yzqFile);
        Approval approval = approvalService.getById(approvalId);
        approval.setApprovalDatabase(yzqFile.getId());
        return approvalService.updateById(approval);
    }

    @Override
    public Approval getApprovalOpinion(Long proId) {
        List<Approval> approvalList = approvalService.lambdaQuery().eq(Approval::getApprovalType, Approval.APPROVAL_TYPE_PROJECT_MANAGE)
                .eq(Approval::getProjectId, proId)
                .eq(Approval::getApprovalNode, ProjectStatusEnum.COMMENTS_SUMMARY_TO_BE_APPROVED.get().getNode())
                .orderByDesc(Approval::getCreateTime).list();
        if(StringUtils.isNotEmpty(approvalList)){
            return approvalList.get(0);
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int returnRepeated(Long proId,String approvalOpinion) {
        ProjectManagement management = projectManagementMapper.selectById(proId);
        Assert.isTrue(StringUtils.isNotNull(management),"未找到该项目信息");
        Assert.isTrue(ProjectStatusEnum.ARRANGE_REVIEW_MEETING_TO_BE_EXTRACTED.get().getStatus().equals(management.getIsState()),
                "项目状态必须为待抽取专家时，才能退回重申！！！");
        //审核进程更新安排评审会议节点
        List<Approval> approvalList = approvalService.lambdaQuery()
                .eq(Approval::getApprovalNode, ProjectStatusEnum.ARRANGE_REVIEW_MEETING_TO_BE_EXTRACTED.get().getNode())
                .eq(Approval::getProjectId,management.getProId())
                .orderByDesc(Approval::getCreateTime).list();
        if(StringUtils.isNotEmpty(approvalList)){
            Approval approval = approvalList.get(0);
            approval.setEndTime(LocalDateTime.now());
            approval.setApprovalOpinion(approvalOpinion);
            approval.setApprovalOperator(String.valueOf(SecurityUtils.getNickName()));
            approval.setApprovalStatus(ProjectStatusEnum.ARRANGE_REVIEW_TO_BE_REBACK.get().getStatus());
            approvalService.updateById(approval);
        }
        //新增方案申报节点
        approvalService.save(new Approval(IdUtils.snowId(),management.getProId(),ProjectStatusEnum.SCHEME_DECLARATION_TO_BE_SUBMITTED.get().getStage(),
                ProjectStatusEnum.SCHEME_DECLARATION_TO_BE_SUBMITTED.get().getNode(),LocalDateTime.now(),null,null,ProjectStatusEnum.SCHEME_DECLARATION_TO_BE_SUBMITTED.get().getStatus(),
                "/",null, null,null, LocalDateTime.now(),Approval.APPROVAL_TYPE_PROJECT_MANAGE));

        //项目状态更新为方案审核待提交
        management.setIsState(ProjectStatusEnum.SCHEME_DECLARATION_TO_BE_SUBMITTED.get().getStatus());
        management.setNode(ProjectStatusEnum.SCHEME_DECLARATION_TO_BE_SUBMITTED.get().getNode());
        //同步项目数据到项目信息表中
        approvalService.synchronizationProjectInfo(management);
        return projectManagementMapper.updateById(management);
    }

    private JSONObject testValue(){
        JSONObject json=new JSONObject();
        //CPU利用率均值
        json.put("cpuAvg",0.41);
        //CPU利用率峰值
        json.put("cpuMax",0.55);
        //内存利用率均值
        json.put("memoryAvg",0.45);
        //内存利用率峰值
        json.put("memoryMax",0.66);
        //硬盘利用率均值
        json.put("hardAvg",0.43);
        //硬盘利用率峰值
        json.put("hardMax",0.56);
        //政务服务资源目录个数
        json.put("resourceCatalogCnt",5);
        //政务服务数据资源个数
        json.put("dataResourceCnt",2);
        //总访问量
        json.put("pvCnt",23000);
        //单日访问峰值
        json.put("dayVisitCnt",1000);
        //连续访问最长时间(天)
        json.put("maxDurationPersistentVisit",34);
        //未访问最长时间(天)
        json.put("maxDurationWithoutVisit",66);
         return json;
    }
}
